package com.ipay.wechat.controller;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.ipay.entity.BizSequenceType;
import com.ipay.utils.Constant;
import com.ipay.utils.DateUtils;
import com.ipay.utils.MathUtil;
import com.ipay.wechat.interceptor.Token;
import com.ipay.wechat.pojo.Cashiers;
import com.ipay.wechat.pojo.PayorderEntity;
import com.ipay.wechat.service.CashiersService;
import com.ipay.wechat.service.PayorderService;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.ipay.service.impl.DefaultSequenceManager;
import com.ipay.utils.R;
import com.ipay.utils.StringUtil;
import com.ipay.wechat.pojo.MerchantInfo;
import com.ipay.wechat.pojo.TradeRecord;
import com.ipay.wechat.service.ApplyService;
import com.ipay.wechat.service.TradeRecordService;

/***
 *
 *
 * 交易中心相关的业务处理
 *
 * @data 2017.08.31
 * @author shi.wu
 *
 */
@Controller
public class TradingController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private TradeRecordService tradeRecordService;
    @Autowired
    private DefaultSequenceManager sequenceManager;
    @Autowired
    private PayorderService payorderService;
    @Autowired
    private CashiersService cashiersService;

    /**
     * 跳转到交易中心
     *
     * @param request
     * @return
     */
    @RequestMapping("/trading/center")
    public ModelAndView isApply(HttpServletRequest request, ModelMap map) {
        String openid = (String) request.getSession().getAttribute("openid");
        String resource = (String) request.getParameter("resource");//来源
        String status = (String) request.getParameter("status");//支付状态
        String orderdateBegin = (String) request.getParameter("orderdateBegin");//开始时间
        String orderdateEnd = (String) request.getParameter("orderdateEnd");//结束时间
        logger.info("===========openid:" + openid + "===========resource:" + resource + "===========status:" + status + "===========orderdateBegin:" + orderdateBegin + "===========orderdateEnd:" + orderdateEnd);
        if (openid == null || "".equals(openid)) {
            return new ModelAndView("login.jsp");
        }
        // 根据openid查询商户订单时间分组数据
        TradeRecord payorder = new TradeRecord();
        if (StringUtil.isNotEmpty(resource)) {
            String[] resourceSz = resource.split(",");
            List<String> list = Arrays.asList(resourceSz);
            payorder.setResourceList(list);
        }
        if (StringUtil.isNotEmpty(status)) {
            String[] statusSz = status.split(",");
            List<String> list = Arrays.asList(statusSz);
            payorder.setStatusList(list);
        }
        if (StringUtil.isNotEmpty(orderdateBegin)) {
            payorder.setOrderdateBegin(orderdateBegin + " 00:00:01");
        }
        if (StringUtil.isNotEmpty(orderdateEnd)) {
            payorder.setOrderdateEnd(orderdateEnd + " 23:59:59");
        }
        //查询当前用户信息（主要判断是1商户还是2收款员）
        Map<String, Object> mapDatetrade = new HashMap<>();
        Cashiers cashiers = cashiersService.findCashierByOpenid(openid, Constant.Status.ENABLE.getValue());
        if (cashiers != null) {
            if (StringUtil.isNotEmpty(cashiers.getRole()) && cashiers.getRole() == Constant.ROLE_SH) { //商户
                payorder.setOpenid(openid);
                mapDatetrade.put("openid", openid);
            } else if (StringUtil.isNotEmpty(cashiers.getRole()) && cashiers.getRole() == Constant.ROLE_SYY) { //收款员
                payorder.setUserid(cashiers.getId());
                mapDatetrade.put("userid", cashiers.getId());
            }
            //日期时间段
            List<String> dateGroupingList = tradeRecordService.findDateGrouping(payorder);
            // 查询商户订单信息
            List<TradeRecord> tradeRecordList = tradeRecordService.findTradeRecordPage(payorder);
            // /今日交易金额
            BigDecimal todaySumAmount = tradeRecordService.findTodaySumAmount(mapDatetrade);
            if (todaySumAmount == null) {
                todaySumAmount = BigDecimal.valueOf(0);
            }
            // /成功交易笔数
            Integer countRecord = tradeRecordService.findCountRecord(mapDatetrade);
            if (countRecord == null) {
                countRecord = 0;
            }
            //扇形统计图数据查询 queryMerchantInfoList
            String title = "";//统计图title
            BigDecimal sumAmount = new BigDecimal("0");
            List<Map<String, String>> tradeListMap = new ArrayList<Map<String, String>>();//商户扇形统计图
            List<Map<String, Object>> cashiersList = new ArrayList<Map<String, Object>>();//商户下各收款员统计图
            TradeRecord tradeRecord = new TradeRecord();
            tradeRecord.setOpenid(openid);


            if (StringUtil.isNotEmpty(cashiers.getRole()) && cashiers.getRole() == Constant.ROLE_SH) { //商户
                List<Map<String, String>> tradeMapList = tradeRecordService.queryMerchantInfoList(tradeRecord);
                //[{drilldown: "小小店铺2",name: "小小店铺2",y: 53.61}, {drilldown: "阿里巴巴",name: "阿里巴巴",y: 58.47}, {drilldown: "AA",name: "AA",y: 60.89}]
                for (Map<String, String> tradeMap : tradeMapList) {
                    Map<String, String> newTradeMap = new HashMap<String, String>();
                    newTradeMap.put("drilldown", tradeMap.get("shopname"));
                    newTradeMap.put("name", tradeMap.get("shopname"));
                    newTradeMap.put("y", tradeMap.get("sumAmount"));
                    tradeListMap.add(newTradeMap);
                    sumAmount = sumAmount.add(MathUtil.getBigDecimal(tradeMap.get("sumAmount")));
                }
                tradeRecord.setTypes("types");//区分查询商户信息还是商户下收款员信息（为空查询商户订单统计信息）
                List<Map<String, String>> tradeCashiersMapList = tradeRecordService.queryMerchantInfoList(tradeRecord);
                //[{id: "小小店铺2",name: "小小店铺2",data: [{name: "v8.0", y: 26.61}, {name: "v9.0", y: 16.96}, {name: "v6.0", y: 6.4}, {name: "v7.0",y: 3.55}, {name: "v5.0", y: 0.09}]}]
                if (tradeMapList.size() > 1) {
                    for (Map<String, String> tradeMap : tradeMapList) {
                        Map<String, Object> newTradeMap = new HashMap<String, Object>();
                        newTradeMap.put("id", tradeMap.get("shopname"));
                        newTradeMap.put("name", tradeMap.get("shopname"));
                        List<Map<String, String>> cashiersListMap = new ArrayList<Map<String, String>>();
                        for (Map<String, String> tradeCashiersMap : tradeCashiersMapList) {
                            if (tradeMap.get("shopname").equals(tradeCashiersMap.get("shopname"))) {
                                Map<String, String> cashiersMap = new HashMap<String, String>();
                                cashiersMap.put("name", tradeCashiersMap.get("name"));
                                cashiersMap.put("y", tradeCashiersMap.get("sumAmount"));
                                cashiersListMap.add(cashiersMap);
                            }
                        }
                        newTradeMap.put("data", cashiersListMap);
                        cashiersList.add(newTradeMap);
                    }
                    title = "各商户今日交易";
                } else if (tradeMapList.size() == 1) {
                    for (Map<String, String> tradeCashiersMap : tradeCashiersMapList) {
                        Map<String, Object> newTradeMap = new HashMap<String, Object>();
                        newTradeMap.put("drilldown", tradeCashiersMap.get("shopname"));
                        newTradeMap.put("name", tradeCashiersMap.get("shopname"));
                        newTradeMap.put("y", tradeCashiersMap.get("sumAmount"));
                        cashiersList.add(newTradeMap);
                    }
                    title = "商户各收款员交易";
                }
            } else if (StringUtil.isNotEmpty(cashiers.getRole()) && cashiers.getRole() == Constant.ROLE_SYY) { //收款员
                TradeRecord tradeRecd = new TradeRecord();
                tradeRecd.setUserid(cashiers.getId());
                List<Map<String, String>> tradeRecdList = tradeRecordService.queryCategoryAmount(tradeRecd);

                for (Map<String, String> tradeMap : tradeRecdList) {
                    Map<String, String> newTradeMap = new HashMap<String, String>();
                    String value = "";
                    if (Constant.CATEGORY_ZF.equals(tradeMap.get("category"))) {
                        value = "支付";
                    } else if (Constant.CATEGORY_TK.equals(tradeMap.get("category"))) {
                        value = "退款";
                    }
                    newTradeMap.put("drilldown", value);
                    newTradeMap.put("name", value);
                    newTradeMap.put("y", tradeMap.get("sumAmount"));
                    tradeListMap.add(newTradeMap);
                }
                title = "今日收支详情";
            }
            String bool = "error";
            if (tradeListMap.size() != 0) {
                bool = "change";
                if (tradeListMap.size() != 1) {
                    String seriesJson = JSONArray.fromObject(tradeListMap).toString();
                    logger.info(seriesJson);
                    map.put("seriesJson", seriesJson);
                    bool = "success";
                }
                String drilldownJson = JSONArray.fromObject(cashiersList).toString();
                logger.info(drilldownJson);
                map.put("drilldownJson", drilldownJson);
                if (StringUtil.isNotEmpty(cashiers.getRole()) && cashiers.getRole() == Constant.ROLE_SH) { //商户
                    if (sumAmount.compareTo(new BigDecimal("0")) < 1) {
                        bool = "error";
                    }
                }
            }
            map.put("bool", bool); //结束时间

            SimpleDateFormat df = new SimpleDateFormat("MM-dd");
            String today = df.format(new Date());
            map.put("today", today); // 系统当前时间
            map.put("dateGroupingList", dateGroupingList); // 日期分组
            map.put("tradeRecordList", tradeRecordList); // 商户所有收款信息
            map.put("todaySumAmount", todaySumAmount); // 今日交易金额
            map.put("countRecord", countRecord); // 成功交易笔数
            map.put("payorder", payorder); //页面传入参数
            map.put("resource", resource); ////来源
            map.put("status", status); ////支付状态
            map.put("orderdateBegin", orderdateBegin); //开始时间
            map.put("orderdateEnd", orderdateEnd); //结束时间
            
            if(StringUtil.isEmpty(orderdateBegin)){
            	map.put("dateStartLong", ""); //结束时间Long
            }else{
            	Long dateStartLong = DateUtils.convertTimeToLong(orderdateBegin);
            	map.put("dateStartLong", dateStartLong); //结束时间Long
            }
            if(StringUtil.isEmpty(orderdateEnd)){
            	map.put("dateEndLong", ""); //结束时间Long
            }else{
            	Long dateEndLong = DateUtils.convertTimeToLong(orderdateEnd);
            	map.put("dateEndLong", dateEndLong); //结束时间Long
            }
            
            
            map.put("title", title); //结束时间
            return new ModelAndView("tradingcenter.jsp");
        } else {
            return new ModelAndView("login.jsp");
        }
    }

    /**
     * 订单详情
     *
     * @param recordNo 订单编号
     * @param request
     * @param map
     * @return
     */
    @RequestMapping("/trading/details")
    public ModelAndView details(@RequestParam String recordNo,
                                HttpServletRequest request, ModelMap map) throws ParseException {
        String openid = (String) request.getSession().getAttribute("openid");

        Cashiers cashiers = cashiersService.findCashierByOpenid(openid, Constant.Status.ENABLE.getValue());
        request.setAttribute("ipayprodauthority", cashiers.getAuthority());
        //订单信息
        TradeRecord dateGroupingTk = tradeRecordService.findTradeRecordDetails(recordNo);
        map.put("dateGroupingTk", dateGroupingTk);
        if (dateGroupingTk != null && StringUtil.isNotEmpty(dateGroupingTk.getOrderdate())) {
            if (StringUtil.isNotEmpty(dateGroupingTk.getCategory()) && Constant.CATEGORY_ZF.equals(dateGroupingTk.getCategory())) { //支付进入
                ///查询订单是否申请的退款
                boolean bool = false;
                if (StringUtil.isNotEmpty(dateGroupingTk.getRecordNo())) {
                    //查询下已退款金额
                    Map<String, Object> mapTradeRec = new HashMap<>();
                    mapTradeRec.put("orderId", dateGroupingTk.getRecordNo());
                    BigDecimal refundSumAmount = tradeRecordService.findRefundSumAmount(mapTradeRec);
                    if (refundSumAmount == null) {
                        refundSumAmount = BigDecimal.valueOf(0);
                    }
                    map.put("refundSumAmount", refundSumAmount);
                    if (refundSumAmount.compareTo(dateGroupingTk.getAmount()) == -1) { //总退款金额  和订单总金额对比  结果是:-1 小于,0 等于,1 大于
                        bool = true;
                    }
                }
                //判断是否为当天
                Date date = new Date();
                SimpleDateFormat df = new SimpleDateFormat("MM-dd");
                SimpleDateFormat dfymd = new SimpleDateFormat("yyy-MM-dd");
                SimpleDateFormat dfymdhms = new SimpleDateFormat("yyy-MM-dd hh:mm:ss");
                String today = df.format(date);
                String orderDate = df.format(dateGroupingTk.getOrderdate());
                if ((today.equals(orderDate)) && bool) { //判断是否为当天
                    String dateStr = dfymd.format(date);
                    Date dfymdhmsDate = dfymdhms.parse(dateStr + " 23:45:00");///每天的23点45后不能进行退款处理(加这么一个限制免的出现问题)
                    long timec = date.getTime() - dfymdhmsDate.getTime();
                    System.out.println(date.getTime() + "  -   " + dfymdhmsDate.getTime() + " = " + timec);
                    if (timec > 0) {
                        bool = false;
                    }
                }else{
                    bool = false;
                }
                //今日交易金额
                Map<String, Object> mapDatetrade = new HashMap<>();
                mapDatetrade.put("openid", openid);
                BigDecimal todaySumAmount = tradeRecordService.findTodaySumAmount(mapDatetrade);
                if (todaySumAmount == null) {
                    todaySumAmount = BigDecimal.valueOf(0);
                }
                if (dateGroupingTk.getAmount().compareTo(todaySumAmount) == 1) { //结果是:-1 小于,0 等于,1 大于
                    bool = false;
                }
                map.put("tkButtonShow", bool);
                return new ModelAndView("tradingDetails.jsp");
            } else { //(dateGroupingTk!=null&&dateGroupingTk.getCategory().intValue()==1)
                TradeRecord dateGrouping = tradeRecordService
                        .findTradeRecordDetails(dateGroupingTk.getOrderId());
                map.put("dateGrouping", dateGrouping);
                return new ModelAndView("showRefund.jsp");
            }
        } else {
            return new ModelAndView("/trading/center");
        }
    }

    /**
     * 订单退款进入
     *
     * @param recordNo 订单编号
     * @param request
     * @param map
     * @return
     */
    @RequestMapping("/trading/toRefund")
    @Token(save = true)
    public ModelAndView toRefund(@RequestParam String recordNo,
                                 HttpServletRequest request, ModelMap map) {
        String openid = (String) request.getSession().getAttribute("openid");
        TradeRecord dateGrouping = tradeRecordService.findTradeRecordDetails(recordNo);
        map.put("dateGrouping", dateGrouping);
        boolean bool = false;
        if (dateGrouping != null && StringUtil.isNotEmpty(dateGrouping.getRecordNo())) {
            //查询下已退款金额
            Map<String, Object> mapTradeRec = new HashMap<>();
            mapTradeRec.put("orderId", dateGrouping.getRecordNo());
            BigDecimal refundSumAmount = tradeRecordService.findRefundSumAmount(mapTradeRec);
            if (refundSumAmount == null) {
                refundSumAmount = BigDecimal.valueOf(0);
            }
            map.put("refundSumAmount", refundSumAmount);
            if (refundSumAmount.compareTo(dateGrouping.getAmount()) == -1) { //结果是:-1 小于,0 等于,1 大于
                bool = true;
            }

            //今日交易金额
            Map<String, Object> mapDatetrade = new HashMap<>();
            mapDatetrade.put("openid", openid);
            BigDecimal todaySumAmount = tradeRecordService.findTodaySumAmount(mapDatetrade);
            if (todaySumAmount == null) {
                todaySumAmount = BigDecimal.valueOf(0);
            }
            if (dateGrouping.getAmount() != null && dateGrouping.getAmount().compareTo(todaySumAmount) == 1) { //结果是:-1 小于,0 等于,1 大于
                bool = false;
            }
            map.put("tkButtonShow", bool);
            String refundNo = DefaultSequenceManager.get().next(BizSequenceType.TRANSQ);//生成退款订单号
            map.put("refundNo", refundNo);
            return new ModelAndView("toRefund.jsp");
        } else {
            return new ModelAndView("pay/payError.jsp").addObject("errorMesage", "订单信息错误");
        }
    }
}
